<?php
    namespace app\listen\controller;
    use app\listen\model\Qrcode;

    class WX extends \app\common\controller\Base{
        private $qrcodeM;
        function getQrcodeM(): Qrcode {
            if (empty($this->qrcodeM)) {
                $this->qrcodeM = new Qrcode();
            }
            return $this->qrcodeM;
        }
        public function getWxcode() {

            $data = $this->getParams();
            $width = $data['width'] ?? 430;
            $page =  $data['page'] ?? 'pages/home/home';
            $auto_color = $data['auto_color']?? false;
            $line_color = $data['line_color']??'{"r":"0","g":"0","b":"0"';
            $qrcode = new \app\WXQRCode();
            $scene = $data['scene']??'34,S853EE4QRP';
            $post_data =
                array(
                    'page' => $page,
                    'scene' => $scene

                );

            $fileName = md5($page.$width.$line_color.$auto_color.$scene);
            // 检查数据库，有则返回
            $d = $this->getQrcodeM()->findQrcode($fileName);
             if (!empty($d) && !empty($d['path'])) {
                 return api_return(1, $d);
             }
            if (!file_exists("qrcode")) {
                mkdirs("qrcode");
            }
            // 下载二维码，并存放在本地
            if (!file_exists("qrcode".$fileName)) {
                $file = fopen('qrcode/'.$fileName, 'w');
                $result = $qrcode->getWxcode($post_data);
                if (!empty($result['data'])) {
                    fwrite($file, $result['data']);
                    fclose($file);
                } else {
                    return api_return(-1, $result);
                }

            }
            // 上传七牛
            $result2 = $this->_qiniuPng('qrcode/'.$fileName, 'qrcode');
             if (!empty($result2) && !empty($result2['data']) && !empty($result2['status']) && $result2['status']===1) {
//                 print_r(json_encode($result2));die;
                 $fl = $this->getQrcodeM()->save([
                     'id'=>$fileName,
                     'path'=>str_replace("http://","https://", $result2['data']),
                 ]);
             } else {
                 print_r(json_encode($result2));die;
             }
            return api_return(1, $this->getQrcodeM()->findQrcode($fileName));
        }
    }